<template>
  <div class="watermark-container" v-watermark="watermarkOptions">
    <div class="print-section" ref="printSectionRef">
      <div class="title-wrap">
        <h1 class="title">水印+打印</h1>
        <div class="btn-wrap" id="btnWrap">
          <el-button
            class="btn"
            type="primary"
            style="margin-right: 10px"
            @click="printHanlder"
            >打印</el-button
          >
          <el-button type="primary" @click="createPdf">生成pdf</el-button>
          <el-button type="primary" @click="toImgPrint"
            >生成图片再打印</el-button
          >
        </div>
      </div>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="date" label="Date" width="150" />
        <el-table-column label="Delivery Info">
          <el-table-column prop="name" label="Name" width="120" />
          <el-table-column label="Address Info">
            <el-table-column prop="state" label="State" width="120" />
            <el-table-column prop="city" label="City" width="120" />
            <el-table-column prop="address" label="Address" />
            <el-table-column prop="zip" label="Zip" width="120" />
          </el-table-column>
        </el-table-column>
      </el-table>
      <div class="watermark" ref="watermarkRef"></div>
    </div>
  </div>
  <img src="" ref="imgRef" alt="" />
</template>

<script setup lang="ts">
import { getStyleString } from './index';
import printJS from 'print-js';
import { reactive, ref } from 'vue';
import { generateWatermark } from '../../directive/watermark';
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';

const watermarkOptions = {
  text: '测试水印',
  fontSize: 20,
  color: 'rgba(0,0,0,0.2)',
  angle: -20,
  padding: 80
};

const tableData = reactive<any[]>([]);

for (let i = 0; i < 100; i++) {
  tableData.push({
    date: i,
    name: 'Tom',
    state: 'California',
    city: 'Los Angeles',
    address: 'No. 189, Grove St, Los Angeles',
    zip: 'CA 90036'
  });
}
const printSectionRef = ref();
const watermarkRef = ref();

const printHanlder = () => {
  const base64Url = generateWatermark('测试水印');
  watermarkRef.value.style.backgroundImage = `url(${base64Url})`;
  printJS({
    printable: printSectionRef.value,
    type: 'html',
    targetStyle: '*',
    targetStyles: ['*'],
    // header: '<h1>测试打印</h1>',
    // css: './index.css',
    style: getStyleString(),
    scanStyles: true,
    maxWidth: 1000,
    // documentTitle: '测试打印'
    onLoadingEnd: () => {}
  });
};
const imgRef = ref();
/** a4纸的尺寸[595.28,841.89], 单位毫米 */
const [PAGE_WIDTH, PAGE_HEIGHT] = [595.28, 841.89];

const createPdf = () => {
  html2canvas(printSectionRef.value, {
    useCORS: true,
    scale: 2,
    allowTaint: true,
    onclone: (doc, ele) => {
      const btnWrap = doc.getElementById('btnWrap')!;
      btnWrap.style.display = 'none';
      const base64Url = generateWatermark('测试水印');
      const div = doc.createElement('div');
      div.style.cssText = `
        position: absolute;
        z-index: 9999;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-image: url(${base64Url});
        background-repeat: repeat;
      `;
      ele.appendChild(div);
    }
  }).then((canvas) => {
    const pdf = new jsPDF({
      unit: 'pt',
      format: 'a4',
      orientation: 'portrait'
    });

    const ctx = canvas.getContext('2d')!;
    let imgHeight = (canvas.width / PAGE_WIDTH) * PAGE_HEIGHT; // 按A4纸比例换算一页图像的像素高度

    let rendererdHeight = 0;
    while (rendererdHeight < canvas.height) {
      let page = document.createElement('canvas');
      page.width = canvas.width;
      page.height = Math.min(imgHeight, canvas.height - rendererdHeight); // 可能不足一页
      page
        .getContext('2d')
        ?.putImageData(
          ctx.getImageData(0, rendererdHeight, canvas.width, page.height),
          0,
          0
        );
      pdf.addImage(
        page.toDataURL('image/jpeg', 1.0),
        'JPEG',
        0,
        0,
        PAGE_WIDTH,
        Math.min(PAGE_HEIGHT, (PAGE_WIDTH / page.width) * page.height)
      );
      rendererdHeight += imgHeight;
      if (rendererdHeight < canvas.height) {
        pdf.addPage();
      }
    }
    // pdf.autoPrint(); // 打开时自动打印
    pdf.save('pdf-example.pdf');
  });
};

const toImgPrint = () => {
  html2canvas(printSectionRef.value, {
    useCORS: true,
    scale: 2,
    allowTaint: true,
    onclone: (doc, ele) => {
      const btnWrap = doc.getElementById('btnWrap')!;
      btnWrap.style.display = 'none';
      const base64Url = generateWatermark('测试水印');
      const div = doc.createElement('div');
      div.style.cssText = `
        position: absolute;
        z-index: 9999;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-image: url(${base64Url});
        background-repeat: repeat;
      `;
      ele.appendChild(div);
    }
  }).then((canvas) => {
    const url = canvas.toDataURL();
    printJS({
      printable: url, // 要打印的id
      type: 'image',
      style:
        '@media print { @page {size: auto; margin: 0; } body{margin:0 5px}}' //去除页眉页脚
    });
  });
};
</script>
<style lang="scss" scoped>
.watermark-container {
  width: 850px;
  margin: 0 auto;
  padding: 20px 0;
  .title-wrap {
    text-align: center;
    margin-bottom: 20px;
    position: relative;
    .btn-wrap {
      position: absolute;
      right: 0;
      top: 50%;
      transform: translate(0, -50%);
    }
  }
  .print-section {
    position: relative;
    .watermark {
      display: none;
      position: absolute;
      width: 100%;
      height: 100%;
      top: 0;
      left: 0;
      background-repeat: repeat;
      pointer-events: none;
      z-index: 9999;
    }
  }
}
</style>
